<?php

/**
 * 接口请求服务
 */

namespace End01here\EasySms\Traits;

use Psr\Http\Message\ResponseInterface;

/**
 * Trait HasHttpRequest.
 */
trait HasHttpRequest
{
    /**
     * Make a get request.
     *
     * @param string $endpoint
     * @param array  $query
     * @param array  $headers
     *
     * @return ResponseInterface|array|string
     */
    protected function get($endpoint, $query = [], $headers = [])
    {
        return $this->request(false, $endpoint,$query);
    }

    /**
     * Make a post request.
     *
     * @param string $endpoint
     * @param array  $params
     * @param array  $headers
     *
     * @return ResponseInterface|array|string
     */
    protected function post($endpoint, $params = [], $headers = [])
    {
        return $this->request(true, $endpoint, $params,false);
    }

    /**
     * Make a post request with json params.
     *
     * @param       $endpoint
     * @param array $params
     * @param array $headers
     *
     * @return ResponseInterface|array|string
     */
    protected function postJson($endpoint, $params = [], $headers = [])
    {
        return $this->request(true, $endpoint, $params,true);
    }

    /**
     * Make a http request.
     *
     * @param string $method
     * @param string $endpoint
     * @param array  $options  http://docs.guzzlephp.org/en/latest/request-options.html
     *
     * @return ResponseInterface|array|string
     */
    protected function request($method, $endpoint, $options = [],$is_json=false)
    {
        $curl = curl_init();
        if(empty($method)){
            if(is_array($options)){
                $options= http_build_query($options);
            }
            $endpoint=$endpoint.'?'.$options;
        }
        curl_setopt($curl, CURLOPT_URL, $endpoint);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        if($method){
            curl_setopt($curl, CURLOPT_POST, $method);
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($curl, CURLOPT_POSTFIELDS, $options);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
            if($is_json){
                curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($options)));
            }else{
                curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/x-www-form-urlencoded'));
            }
        }
        $ret = curl_exec($curl);
         return json_decode($ret, true);
    }


}
